package com.tsx.wiki.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.tsx.wiki.dto.CategoryDTO;
import com.tsx.wiki.dto.CategoryPageDTO;
import com.tsx.wiki.mapper.CategoryMapper;
import com.tsx.wiki.pojo.Category;
import com.tsx.wiki.result.PageResult;
import com.tsx.wiki.service.CategoryService;
import com.tsx.wiki.vo.CategoryVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Resource
    private CategoryMapper categoryMapper;

    @Override
    public PageResult<Category> page(CategoryPageDTO categoryPageDTO) {
        PageHelper.startPage(categoryPageDTO.getCurrent(), categoryPageDTO.getPageSize());
        Page<Category> page = categoryMapper.selectAllByPage(Category.builder().name(categoryPageDTO.getName()).build());
        PageResult<Category> pageResult = new PageResult<>();
        pageResult.setRecords(page.getResult());
        pageResult.setTotal(page.getTotal());
        return pageResult;
    }

    @Override
    public List<Category> list(CategoryDTO categoryDTO) {
        Category category = toCategory(categoryDTO);
        return categoryMapper.selectAll(category);
    }

    @Override
    public CategoryVo selectById(Long id) {
        Category category = categoryMapper.selectById(id);
        return CategoryVo.builder()
                .id(category.getId())
                .name(category.getName())
                .sort(category.getSort())
                .parent(category.getParent())
                .build();
    }

    @Override
    public void update(CategoryDTO categoryDTO) {
        Category category = toCategory(categoryDTO);
        categoryMapper.update(category);
    }

    @Override
    public void save(CategoryDTO categoryDTO) {
        Category category = toCategory(categoryDTO);
        categoryMapper.save(category);
    }

    @Override
    public void deleteById(Long id) {
        categoryMapper.deleteById(id);
    }

    private Category toCategory(CategoryDTO categoryDTO) {
        return Category.builder()
                .id(categoryDTO.getId())
                .name(categoryDTO.getName())
                .sort(categoryDTO.getSort())
                .parent(categoryDTO.getParent())
                .build();
    }
}




